package com.seek.quartz;

import com.alibaba.fastjson.JSON;
import com.seek.authcheck.constants.AuthConstant;
import com.seek.authcheck.constants.AuthProductEnum;
import com.seek.cache.CacheUtil;
import com.seek.constants.ApiParamsConstant;
import com.seek.constants.RedisCustomerConstant;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.service.BizFlowService;
import com.seek.service.CustomerService;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;
import com.seek.util.Push2SingleUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户认证状态更新
 * Created by weh on 2017/7/5.
 */
public class CustomerAuthStatusQuartz {

  private static final Logger logger = LoggerFactory.getLogger(CustomerAuthStatusQuartz.class);

  @Resource
  private BizFlowService bizFlowService;

  @Resource
  private CustomerService customerService;

  @Resource
  private Push2SingleUtil push2SingleUtil;

  private static final String LAST_UPDAT_TIME = "lastAuthCheckTime";

  @SuppressWarnings("unchecked")
  /**更新客户信息状态，逐条更新，每次新启事物**/
  public void run() {
    Date lastTime = null;
    Date curTime = null;
    String authCheckTime = CacheUtil.getRedisData(LAST_UPDAT_TIME);
    if (StringUtils.isEmpty(authCheckTime)) {
      long value = DateUtil.getMinuteAfter(-40);
      lastTime = new Date(value);
    } else {
      lastTime = new Date(CommonUtil.getLongValue(authCheckTime));
    }

//    logger.info("上次执行时间:{}", DateUtil.getFormattedDate(lastTime, "yyyy-MM-dd HH mm ss"));
    curTime = DateUtil.dateAdd(DateUtil.DATE_INTERVAL_MINUTE, new Date(), -20);
//    logger.info("本次执行时间:{}", DateUtil.getFormattedDate(curTime, "yyyy-MM-dd HH mm ss"));

    if (lastTime.after(curTime)) {
      logger.warn("上次执行时间:{},大于当前执行时间{},任务结束",
          DateUtil.getFormattedDate(lastTime, "yyyy-MM-dd HH mm ss"),
          DateUtil.getFormattedDate(curTime, "yyyy-MM-dd HH mm ss"));
    }

    String getBizSql =
        "select company_id as companyId, customer_id as customerId,biz_no as bizNo,biz_type as "
            + "bizType,status from t_biz_flow where deleted = ? "
            + "and modify_time > ? and modify_time <= ?";
    List<Map<String, Object>> bizFlows = bizFlowService
        .findMapBySql(getBizSql, new Object[]{0, lastTime, curTime});

    if (CollectionUtils.isNotEmpty(bizFlows)) {
      for (Map<String, Object> bizFlow : bizFlows) {
        AuthProductEnum product = AuthProductEnum
            .getAuthProductByProcuctCode(bizFlow.get("bizType").toString());
        String status = (String) bizFlow.get("status");
        if (null != product && (!StringUtils.equals(status, "1"))) {
          process(bizFlow);
        }
      }
    }
    CacheUtil.putRedisData(LAST_UPDAT_TIME, String.valueOf(curTime.getTime()));

  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void process(Map<String, Object> bizFlow) {
    try {
      String productCode = (String) bizFlow.get("bizType");
      Long companyId = CommonUtil.getLongValue(bizFlow.get("companyId"));
      Long customerId = CommonUtil.getLongValue(bizFlow.get("customerId"));
      String bizNo = bizFlow.get("bizNo").toString();
      String updateColumn = getUpdateColumn(productCode);
      int result = customerService
          .updateAuthStatus(updateColumn, AuthConstant.AUTH_FAIL, AuthConstant.AUTH_PROCESS,
              customerId, companyId);
      bizFlowService
          .executeUpdate(
              "update t_biz_flow set status = ? ,deleted= ? where biz_no = ? and deleted = ?",
              new Object[]{"0", 1, bizNo, 0});
      if(result >0){
        InterDtoCUser cuser = CacheUtil.getCLoginCache(CacheUtil.getRedisData(RedisCustomerConstant.CUST_KEY_PREFIX+customerId));
        if(null != cuser){
          pushFail(cuser.getClientid(),productCode);
        }
      }
    } catch (Exception e) {
      logger.error("更新客户信息失败,{},", JSON.toJSONString(bizFlow));
      e.printStackTrace();
    }
  }


  /**
   * 根据productCode获取需要更新的字段
   */
  private static String getUpdateColumn(String productCode) {
    String column = "";
    switch (productCode) {
      case "certcard":
        column = "certification_status";
        break;
      case "carrier":
        column = "mobile_status";
        break;
      case "alipay":
        column = "zfb_status";
        break;

      default:
        column = "";
        break;
    }
    return column;
  }

  private void pushFail(String clientId ,String productCode){
    String [] ret = new String[2];
    int type = 0;
    try {
      switch (productCode) {
        case "certcard":
          type = Push2SingleUtil.TYPE_OF_CERTIFY_FAIL;
          ret[0] = "抱歉，您的实名认证超时。请您上传照片进行人工审核";
          ret[1] = "{'appUrl':'huajinbao://auth.list','mTitle':'实名认证超时','logo':'http://huajinbao.b0.upaiyun.com/logo/m_id.png','bText':'继续认证','content':'"+ret[0]+"','type':'"+type+"','createTime':'"+DateUtil.dateFormat(new Date(), DateUtil.DATE_FORMAT_YMDHMS)+"'}";
          break;
        case "carrier":
          type = Push2SingleUtil.TYPE_OF_MOBILE_FAIL;
          ret[0] = "抱歉，您的运营商认证超时，请您重新申请认证";
          ret[1] = "{'appUrl':'huajinbao://auth.list','mTitle':'运营商认证超时','logo':'http://huajinbao.b0.upaiyun.com/logo/m_operator.png','bText':'继续认证','content':'"+ret[0]+"','type':'"+type+"','createTime':'"+DateUtil.dateFormat(new Date(), DateUtil.DATE_FORMAT_YMDHMS)+"'}";
        case "alipay":
          break;
        default:
          break;
      }
      if(StringUtils.isNotEmpty(ret[0]) &&StringUtils.isNotEmpty(ret[1])){
        push2SingleUtil.push2Single(ret[0], clientId, ret[1]);
      }
    }catch (Exception e){
      e.printStackTrace();
      logger.error("clientId:{}消息推送失败,{}",clientId,e);
    }
  }

}
